package mysql

import (
	"aiserver/pkg/models"
	"errors"

	"gorm.io/gorm"
)

var UserExistedError = errors.New("user existed...")

type users struct {
	db *gorm.DB
}

func newUsers(ds *datastore) *users {
	return &users{ds.db}
}

func (u *users) GetUser(username string) (*models.User, error) {
	var user models.User
	if ctx := u.db.Find(&user, "user_name = ?", username); ctx.Error != nil {
		return nil, ctx.Error
	}
	return &user, nil
}

func (u *users) CreateGet(username string, password string, admin bool) (*models.User, error) {
	var user models.User
	if ctx := u.db.Find(&user, models.User{UserName: username}); ctx.Error != nil {
		return nil, ctx.Error
	}
	if user.ID == 0 {
		user.UserName = username
		user.Password = password
		user.Admin = admin
		if ctx := u.db.Create(&user); ctx.Error != nil {
			return nil, ctx.Error
		}
	}
	return &user, nil
}
